'''
Created on Aug 5, 2009

@author: mkiyer
'''

import os
import sys

from veggie.app.chipseq import sw_root
from veggie.app.application import CommandLineApplication

class GLITR(CommandLineApplication):
    '''
    Global Identifier of Target Regions (GLITR) peak-finding algorithm
    http://web.me.com/kaestnerlab1/GLITR
    '''
    _glitr_home = sw_root
    _executable = "perl " + os.path.join(_glitr_home, "GLITR", "GLITR.pl")

    def _getResultPaths(self):
        #basepath = os.path.join(os.path.abspath(self.cwd), self._options['--name'])
        #return {'bed': basepath + '_peaks.bed'}
        print 'result paths called'
        return None

    def _convert_to_glitr_format(self, parser, align_file, output_fhd):
        # parse file for reads that map to this chromosome
        for mappings in parser.parse_file(open(align_file)):
            for match in mappings:
                if not match.maps_to_genome():
                    continue
                if match.chrom == 'chrM':
                    continue            
                strand = None            
                if match.strand == 'F' or match.strand == '+':
                    strand = '+'
                elif match.strand == 'R' or match.strand == '-':
                    strand = '-'
                else:
                    # TODO: exception
                    print 'strand format error', match.strand
                    sys.exit(1)
                # write in glitr format
                output_fhd.write('%s\t%d\t%s\n' % (match.chrom, match.chrom_start, strand))

    def run(self, exper_name, parser, treatment_file, control_file, options=None, cwd=None):
        if cwd:
            self.cwd = cwd
        if options:
            self.addOptions(options)

        # convert treatment to GLITR format
        print 'converting treatment to glitr format'
        chip_path = os.path.join(self.cwd, "%s_CHIP.align" % exper_name)
        if os.path.exists(chip_path):
            print 'skipping CHIP format conversion -- file exists'
        else:
            chip_fhd = open(chip_path, 'w')
            self._convert_to_glitr_format(parser, treatment_file, chip_fhd)
            chip_fhd.close()

        # control control to GLITR format
        print 'converting control to glitr format'
        control_path = os.path.join(self.cwd, "%s_CONTROL.align" % exper_name)
        if os.path.exists(control_path):
            print 'skipping CONTROL format conversion -- file exists'
        else:
            control_fhd = open(control_path, 'w')
            self._convert_to_glitr_format(parser, control_file, control_fhd)
            control_fhd.close()
         
        # setup GLITR command-line parameters
        self.addOption('--CHIP', chip_path)
        self.addOption('--CONTROL', control_path)
        self.addOption('--GENOME', 'HG18')
        self.addOption('--GLITR', self._glitr_home)
        
        print self.getCommandLine()
        
        # run GLITR -- invoke the CommandLineApplication __call__() function
        retcode, resultpaths = self()
    
    def tearDown(self):
        '''
        app-specific post-processing and cleanup code
        '''
        result = self._getResultPaths()
        infhd = open(result['bed'])
        basepath = os.path.join(os.path.abspath(self.cwd), self._options['--name'])
        outfhd = open(basepath + '_filtered.bed', 'w')
        print >>sys.stderr, 'filtering _peaks.bed...'
        BEDParser.filterFile(infhd, outfhd, filterfunc=filter_neg_positions)